const express = require('express')
const path = require('path')
const favicon = require('serve-favicon')
const logger = require('morgan')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const apicache = require('apicache')
const cors = require('cors')
// const csurf = require('csurf')
const session = require('express-session')
const MySQLStore = require('express-mysql-session')(session)
const compression = require('compression')
const htmlMinifier = require('html-minifier')
const app = express()
const cache = apicache.middleware

const config = require('./config')
const artImports = require('./util/artImports')

// view engine setup
app.set('views', path.join(__dirname, 'views'))
// app.set('view engine', 'twig')
app.set('view engine', 'html')
app.engine('html', require('express-art-template'))

app.set('view options', {
  debug: process.env.NODE_ENV !== 'production',
  // escape 可以防范 XSS 攻击
  escape: true,
  cache: true,
  minimize: true,
  // HTML 压缩器。仅在 NodeJS 环境下有效
  htmlMinifier: htmlMinifier,
  // HTML 压缩器配置。参见 https://github.com/kangax/html-minifier
  htmlMinifierOptions: {
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    // 运行时自动合并：rules.map(rule => rule.test)
    ignoreCustomFragments: []
  },
  extname: '.html',
  imports: artImports
})

/** 设置路由中间件 */
app.use(cors())
// compress all responses
app.use(compression())
var sessionStore = new MySQLStore({
  host: config.dbHost,
  port: config.port,
  user: config.dbUser,
  password: config.dbPassword,
  database: config.database
})
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: false,
  store: sessionStore,
  cookie: {
    maxAge: 30 * 60 * 1000 // 有效期，单位是毫秒
  }
}))
// app.use(csurf())
const onlyStatus200 = (req, res) => res.statusCode === 200
app.use(cache('5s', onlyStatus200))
app.use((req, res, next) => {
  // let csrfToken = req.csrfToken()
  // res.cookie('_csrf', csrfToken, { maxAge: 900000, httpOnly: true })
  const proxy = req.query.proxy
  if (proxy) {
    req.headers.cookie = req.headers.cookie + `__proxy__${proxy}`
  }
  next()
})
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use(require('./routes'))
// app.use(require('./routes/music'))
app.use(require('./routes/china_city'))
app.use('/weather', require('./routes/weather'))
app.use('/cvm', require('./routes/cvm'))
// catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found')
  err.status = 404
  next(err)
})
// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}
  // render the error page
  res.status(err.status || 500)
  if (err.status === 404) {
    res.render('404')
  } else {
    res.render('error')
  }
})
// const port = process.env.PORT || 3435
// app.listen(port, () => {
//   console.log('http://localhost:%d', port)
// })
module.exports = app
